<?php
/**
 * Created by PhpStorm.
 * User: dayu
 * Date: 2019/12/16
 * Time: 17:16
 */

namespace data\service;

use data\api\ISecretToken;
use think\cache\driver\Redis;

class SecretToken extends BaseService implements ISecretToken
{
    protected $reids;

    public function __construct()
    {
        $this->redis = new Redis();


    }

    /**
     * 创建令牌
     * @param $secret
     * @return mixed
     */
    public function createToken($secret)
    {
        $random = password_hash($secret, PASSWORD_DEFAULT, ['cost' => 10]);
        $this->redis->set($random, $secret, config('token')['valid']);
        if (!$this->redis->get($random)) {
            return false;
        }
        return $random;
    }


    /**
     * @param $refresh
     * @return bool
     */
    public function disposeToken($refresh,$type=false)
    {
        if($type){
            $userData = $this->redis->get($refresh);
            $this->redis->del($refresh);
        }else{
            $userData = $refresh;
        }
        if ($userData) {
            $random = password_hash(json_encode($userData), PASSWORD_DEFAULT, ['cost' => 10]);
            $userData['token'] = $random;
            $userData['refresh'] = $newRefresh = password_hash(json_encode($userData), PASSWORD_DEFAULT, ['cost' => 10]);
            $array = $userData;
            $this->redis->set($random, $userData, config('token')['valid']);
            unset($userData['token'], $userData['refresh']);
            $this->redis->set($newRefresh, $userData, config('token')['refresh']);
            if (!$this->redis->get($random) && !$this->redis->get($newRefresh)) {
                return false;
            }
            return $array;
        }else{
            return false;
        }
    }


}